package com.bdzl.ecs.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bdzl.ecs.dao.ContractOnlineSignrecDao;
import com.bdzl.ecs.pojo.contractVO;
import com.bdzl.ecs.service.ContractOnlineService;
import com.bdzl.ecs.service.ContractTmplService;
import com.bdzl.ecs.servicefeign.EnterpriseFeignService;
import com.bdzl.ecs.servicefeign.FddCaEntFeignService;
import com.bdzl.ecs.servicefeign.FddCaPersonalFeignService;
import com.bdzl.ecs.servicefeign.OrderFeignService;
import com.bdzl.ecs.util.FddClientBaseUtils;
import com.bdzl.pub.config.Constant;
import com.bdzl.pub.controller.BaseController;
import com.bdzl.pub.entity.data.EnterpriseDO;
import com.bdzl.pub.entity.data.FddCaEntDO;
import com.bdzl.pub.entity.data.FddCaPersonalDO;
import com.bdzl.pub.entity.loan.ContractOnlineDO;
import com.bdzl.pub.entity.loan.ContractOnlineSignrecDO;
import com.bdzl.pub.entity.loan.ContractTmplDO;
import com.bdzl.pub.util.file.BASE64DecodedMultipartFile;
import com.bdzl.pub.util.file.OssUploadFileUtil;
import com.bdzl.pub.util.ip.ipUtils;
import com.bdzl.pub.vo.util.SigningAContractVO;
import com.fadada.sdk.client.FddClientBase;
import com.fadada.sdk.util.crypt.FddEncryptTool;
import com.fadada.sdk.util.http.HttpsUtil;
import org.apache.http.message.BasicNameValuePair;
import org.checkerframework.checker.units.qual.A;
import org.springframework.stereotype.Controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.apache.http.NameValuePair;
import com.bdzl.pub.util.param.PageUtils;
import com.bdzl.pub.util.param.Query;
import com.bdzl.pub.util.param.R;
import com.bdzl.ecs.util.contractUtils.ContractUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 合同表
 *
 * @author yangyicai
 * @email yangyicai@foxmail.com
 * @date 2021-03-23 14:00:08
 */

@Controller
@RequestMapping("/bdzl/contract")
@CrossOrigin("*") //处理跨域请求
public class ContractController extends BaseController {

    @Autowired
    private FddCaPersonalFeignService fddCaPersonalFeignService;
    @Autowired
    private FddCaEntFeignService fddCaEntFeignService;
    @Autowired
    private EnterpriseFeignService enterpriseFeignService;
    @Autowired
    private ContractTmplService contractTmplService;
    @Autowired
    private ContractOnlineService contractOnlineService;
    @Autowired
    private OrderFeignService orderFeignService;
    @Autowired
    private ContractOnlineSignrecDao contractOnlineSignrecDao;

    /**
     * 个人CA申请接口
     * 个人CA申请接口
     *
     * @param name     客户姓名
     * @param email    客户邮箱
     * @param card     客户证件号码
     * @param cardType 证件类型
     *                 0-身份证（默认值）；
     *                 1-护照；
     *                 2-军人身份证；
     *                 6-社会保障卡；
     *                 A-武装警察身份证件；
     *                 B-港澳通行证；
     *                 C-台湾居民来往大陆通行证；
     *                 E-户口簿
     * @param mobile   客户手机号码
     * @return
     */
    @ResponseBody
    @RequestMapping("/CACustomer")
    public String CACustomer(String name, String email, String card, String cardType, String mobile) {
        String response = ContractUtils.CACustomer(name, email, card, cardType, mobile);
        JSONObject jsonObject = JSON.parseObject(response);
        if ("1000".equals(jsonObject.get("code"))) {
            //认证通过，data_fdd_ca_personal 表中添加数据
            FddCaPersonalDO fddCaPersonal = new FddCaPersonalDO();
            fddCaPersonal.setCapCardId(card);
            fddCaPersonal.setCapCustomerId(jsonObject.get("customer_id").toString());
            R r = fddCaPersonalFeignService.save(fddCaPersonal);
        }
        return response;
    }

    /**
     * 客户信息修改接口
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/infoChange")
    public String InfoChange() {
        String response = ContractUtils.InfoChange(Constant.CID, "2747253523@qq.com", "440603199705233432");
        return response;
    }

    /**
     * 企业CA证书申请(免审核模式)
     *
     * @param customerName 企业名称
     * @param email        电子邮箱 可选 可以为null
     * @param mobile       手机号码
     * @param organization 组织机构
     * @param orgId        企业id
     * @return
     */
    @ResponseBody
    @RequestMapping("/syncCompanyAuto")
    public String syncCompanyAuto(String customerName, String email, String mobile, String organization, Integer orgId) {
        FddClientBaseUtils fddClientBaseUtils = new FddClientBaseUtils(Constant.FDD_APPID, Constant.FDD_APPSECRET, Constant.FDD_VERSION, Constant.FDD_CAURL);
        String response = fddClientBaseUtils.syncCompanyAuto(customerName, email, mobile, organization);
        //添加企业CA证书信息  data_fdd_ca_ent
        JSONObject jsonObject = JSON.parseObject(response);
        Map map = null;
        if ("1000".equals(jsonObject.get("code"))) {
            //认证通过，data_fdd_ca_personal 表中添加数据
            R r = enterpriseFeignService.edit(orgId);
            if (r.get("data") != null) {
                map = (Map) r.get("data");
            }

            FddCaEntDO fddCaEntDO = new FddCaEntDO();
            fddCaEntDO.setPceEntNo(map.get("entNo").toString());
            fddCaEntDO.setPceCustomerId(jsonObject.get("customer_id").toString());
            fddCaEntFeignService.save(fddCaEntDO);
        }
        return response;
    }

    /**
     * zhaochunyu
     * 上传合同模板，参数字段 file和doc_url选一个
     *
     * @return
     * @Date 2021年4月26日16:01:20
     */
    @PostMapping("/uploadTemplate")
    @ResponseBody
    public String uploadTemplate(@RequestBody ContractTmplDO contractTmplDO) {
        //模板编号 只允许长度<=32的英文或数字字符
        String template_id = System.currentTimeMillis() + "";
        String docUrl = OssUploadFileUtil.RandomFileName.uploadToOSS(contractTmplDO.getTmplUrl(), "loan/" + "contractUtils");
        String response = ContractUtils.uploadTemplate(template_id, null, docUrl);
        JSONObject json = JSONObject.parseObject(response);
        json.put("template_id", template_id);
        response = json.toJSONString();
        //添加合同模板记录
        contractTmplDO.setTmplUrl(docUrl);
        contractTmplDO.setTmplNo(Long.parseLong(template_id));
        contractTmplDO.setTmplCreuser(super.getUserId());
        contractTmplService.save(contractTmplDO);
        return response;
    }

    /**
     * 2021年4月27日10:56:08
     * 合同生成接口
     *
     * @return {result:返回结果,code:结果代码,msg:描述,download_url:下载地址,viewpdf_url:查看地址}
     * @Parmat contractVO 传参对象，详细信息查看对象
     */

    @PostMapping("/invokeGenerateContract")
    @ResponseBody
    public String invokeGenerateContract(@RequestBody contractVO contractVO) {
        //合同编号 只允许长度<=32的英文或数字字符
        String contract_id = System.currentTimeMillis() + "";
        String response = ContractUtils.invokeGenerateContract(contractVO.getDocTitle(), contractVO.getTemplateId(), contractVO.getFontSize(), contractVO.getFontType(), contractVO.getParamter(), contractVO.getDynamicTables(), contract_id);
        System.out.println(response);//打印结果，解析JSON报文*/
        JSONObject json = JSONObject.parseObject(response);
        json.put("contract_id", contract_id);
        if ("操作成功".equals(json.get("msg"))) {
            ContractOnlineDO contractOnline = new ContractOnlineDO();
            contractOnline.setOnlineConNo(Long.parseLong(contract_id));
            contractOnline.setOnlineConTitle(contractVO.getDocTitle());
            contractOnline.setOnlineTmplId(Long.parseLong(contractVO.getTemplateId()));
            contractOnline.setOnlineFddGetUrl(json.get("viewpdf_url").toString());
            contractOnline.setOnlineFddOnloadUrl(json.get("download_url").toString());
            contractOnline.setOnlineCreuser(super.getUserId());
            int a = contractOnlineService.save(contractOnline);
        }
        response = json.toJSONString();
        return response;
    }


    /**
     * 合同签署接口（手动）
     *
     * @param contractVO
     * @return
     */
    @PostMapping("/invokeExtSign")
    @ResponseBody
    public String invokeExtSign(@RequestBody contractVO contractVO) {
        //交易号
        String transactionId = System.currentTimeMillis() + "";
        contractVO.setTransactionId(transactionId);
        //response 需要重定向的合同签署地址
        String response = ContractUtils.invokeExtSign(contractVO.getTransactionId(), contractVO.getCustomerId(), contractVO.getContractId(), contractVO.getDocTitle(), contractVO.getSignKeyword(), contractVO.getKeywordStrategy(), contractVO.getReturnUrl(), contractVO.getNotifyUrl());
        return response;
    }

    /**
     * 法大大签署回调接口
     *
     * @param transaction_id 交易号
     * @param result_code    签章结果代码3000（签章成功）3001(签章失败)
     * @param result_desc    签章结果描述签章结果描述信息
     * @param download_url   下载地址下载签署后的合同
     * @param viewpdf_url    查看地址查看签署后的合同
     * @param timestamp      请求时间yyyyMMddHHmmss
     * @param msg_digest
     * @return
     */
    @GetMapping("/getfadd")
    public String getfadd(String transaction_id,
                          String result_code,
                          String result_desc,
                          String download_url,
                          String viewpdf_url,
                          String timestamp,
                          String msg_digest, Model model) {
        System.out.println(transaction_id + result_desc
                + download_url
                + viewpdf_url
                + timestamp
                + msg_digest);
        model.addAttribute("transaction_id", transaction_id);
        model.addAttribute("result_code", result_code);
        model.addAttribute("result_desc", result_desc);
        model.addAttribute("download_url", download_url);
        model.addAttribute("viewpdf_url", viewpdf_url);
        model.addAttribute("timestamp", timestamp);
        model.addAttribute("msg_digest", msg_digest);

        Map map =new HashMap();
        map.put("transaction_id", transaction_id);
        map.put("odrNo", transaction_id);
        map.put("result_code", result_code);
        map.put("result_desc", result_desc);
        map.put("download_url", download_url);
        map.put("viewpdf_url", viewpdf_url);
        map.put("timestamp", timestamp);
        map.put("msg_digest", msg_digest);

        //修改签署记录
        Map map1 = new HashMap();
        map1.put("cosTransaction",transaction_id);
        List<ContractOnlineSignrecDO> contractOnlineSignrecDOList = contractOnlineSignrecDao.list(map1);
        for (ContractOnlineSignrecDO contractOnlineSignrecDO:contractOnlineSignrecDOList) {
            contractOnlineSignrecDO.setCosState(1);
            contractOnlineSignrecDao.update(contractOnlineSignrecDO);
        }

       /* orderFeignService.powerOfAttorney(map);*/
        return "success";

    }


    /**
     * 异步回调接口
     *
     * @param transaction_id 交易号
     * @param result_code    签章结果代码3000（签章成功）3001(签章失败)
     * @param result_desc    签章结果描述签章结果描述信息
     * @param download_url   下载地址下载签署后的合同
     * @param viewpdf_url    查看地址查看签署后的合同
     * @param timestamp      请求时间yyyyMMddHHmmss
     * @param contract_id    合同编号
     * @param msg_digest
     * @return
     */
    @GetMapping("/yibugetfadd")
    public String yibugetfadd(String transaction_id,
                     String contract_id,
                     String result_code,
                     String result_desc,
                     String download_url,
                     String viewpdf_url,
                     String timestamp,
                     String msg_digest, Model model) {
        System.out.println(transaction_id + result_desc
                + download_url
                + viewpdf_url
                + timestamp
                + msg_digest);
        model.addAttribute("transaction_id", transaction_id);
        model.addAttribute("result_code", result_code);
        model.addAttribute("result_desc", result_desc);
        model.addAttribute("download_url", download_url);
        model.addAttribute("viewpdf_url", viewpdf_url);
        model.addAttribute("timestamp", timestamp);
        model.addAttribute("msg_digest", msg_digest);

        Map map =new HashMap();
        map.put("transaction_id", transaction_id);
        map.put("odrNo", transaction_id);
        map.put("result_code", result_code);
        map.put("result_desc", result_desc);
        map.put("download_url", download_url);
        map.put("viewpdf_url", viewpdf_url);
        map.put("timestamp", timestamp);
        map.put("msg_digest", msg_digest);
        return "success";
    }



    /**
     * 2021年4月28日15:55:15
     * 客户签署结果查看
     *
     * @param contractId    签署时所传合同编号
     * @param customerId    签署时所传客户编号
     * @param transactionId 签署时所传交易号
     * @return
     */
    @GetMapping("invokeQuerySignResult/{contractId}/{customerId}/{transactionId}")
    @ResponseBody
    public String invokeQuerySignResult(@PathVariable("contractId") String contractId, @PathVariable("customerId") String customerId, @PathVariable("transactionId") String transactionId) {
        String response = ContractUtils.invokeQuerySignResult(contractId, customerId, transactionId);
        return response;
    }

    @GetMapping("invokeContractFilling/{contractId}")
    @ResponseBody
    public String invokeContractFilling(@PathVariable("contractId") String contractId) {
        String response = ContractUtils.invokeContractFilling(contractId);
        return response;
    }

    /**
     * 文档签署接口 (自动签)
     * zhaochunyu
     *
     * @param transaction_id   交易号 1620456132454
     * @param customer_id      客户编号
     * @param client_role      客户劫色 1-接入平台；2-仅适用互金行业担保公司或担保人；3-接入平台客户（互金行业指投资人）；4-仅适用互金行业借款企业或者借款人如果需要开通自动签权限请联系法大大的商务签署补充协议。
     * @param contract_id      合同编号
     * @param doc_title        文档标题
     * @param sign_keyword     定位关键字
     * @param keyword_strategy 关键字签章策略
     * @param notify_url       签署结果异步通知URL
     * @return
     * @Data 2021年5月8日11:31:56
     */
    @PostMapping("invokeExtSignAuto")
    @ResponseBody
    public String invokeExtSignAuto(String transaction_id, String customer_id, String client_role, String contract_id, String doc_title, String sign_keyword, String keyword_strategy, String notify_url) {
        notify_url = "http://192.168.1.42:7002/bdzl/contract/getfadd";
        String response = ContractUtils.invokeExtSignAuto(transaction_id, customer_id, client_role, contract_id, doc_title, sign_keyword, keyword_strategy, notify_url);
        return response;
    }



    /**
     * todo 方案B(法大达推送消息)
     * 对接报件流程，客户申请CA证书，自动生成合同，企业自动盖章，最终生成url发送给客户，客户签章通过，回调平台接口。
     * @param signingAContractVO
     * @return
     */
    @PostMapping("/signingAContract")
    @ResponseBody
    public String signingAContract(@RequestBody @Validated SigningAContractVO signingAContractVO) {
        return   contractTmplService.signingAContract(signingAContractVO,super.getUserId());
    }



    /**
     * 合同推送
     * @param transaction_id  交易号
     * @param contract_id 合同编号
     * @param customer_id 客户编号
     * @param doc_title   文档标题
     * @param sing_keyword   定位关键字
     * @return
     */
    @PostMapping("/pushdocExtsign")
    @ResponseBody
    public String pushdocExtsign(String transaction_id,String contract_id,String customer_id,String doc_title,String sing_keyword){
        return   contractTmplService.pushdocExtsign( transaction_id, contract_id, customer_id, doc_title,sing_keyword);
    }


}
